<script setup lang="ts">
import { Ref, computed, onMounted, ref, toValue, unref } from 'vue'
import { Search, Refresh, CirclePlus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useStore } from '@/pinna';
import { AddFlightInfo, AllOrderInfoRow, EvfaluateRow, FindFlightInfo, FindFlightTableRow, FindMyOrderDetail, reqAddFlightInfo, reqFindEvFaluate, reqFindFlightInfo, reqFindFlightInfoById, reqFindMyOrderDetail, reqFindOrderByFlightId, reqModifyFlightInfo, reqRemoveFlightInfo } from '@/api/AFlight';
const infoStore = useStore()
onMounted(() => {
    findData()
})

// 搜索栏
const pageNo: Ref<number> = ref(1)
const pageSize = ref(10)
const searchFrom = ref<FindFlightInfo>({
    flightNumber: '',
    departureCity: '',
    arrivalCity: '',
    airline: '',
    aircraftType: '',
    departureTime: '',
    arrivalTime: ''
})

const reset = () => {
    searchFrom.value = {
        flightNumber: '',
        departureCity: '',
        arrivalCity: '',
        airline: '',
        aircraftType: '',
        departureTime: '',
        arrivalTime: ''
    }
    findData()
}

const handleSizeChange = (val: number) => {
    pageSize.value = val
    findData()
}

const handleCurrentChange = (val: number) => {
    pageNo.value = val
    findData()
}

const total: Ref<number> = ref(0)
const tableData: Ref<Partial<FindFlightTableRow[]>> = ref([])

const findData = async () => {
    await reqFindFlightInfo({
        pageNo: toValue(pageNo),
        pageSize: toValue(pageSize),
        ...toValue(searchFrom)
    }).then((res: any) => {
        const { code, data, total: tableTotal } = res

        if (code === 200) {
            tableData.value = data
            total.value = tableTotal

        } else {
            ElMessage({
                message: '请求异常',
                type: 'warning'
            })
        }
    })
}

let editId = ref('')

const editRoleInfo = async (id: string) => {
    findRoleInfo(id, 'edit')
    editId.value = id
}

const findRoleInfo = async (id: string, type?: 'edit' | 'add') => {
    await reqFindFlightInfoById({ id }).then((res: any) => {
        const { data } = res
        console.log(data);

        addHsotForm.value = data

        dialogHostTitle.value = type === 'edit' ? '编辑航班信息' : '查看航班信息'
        dialogHost.value = true
    })
}

const deleteRoleInfo = async (id: string) => {
    ElMessageBox.confirm(
        '是否确认删除?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            await reqRemoveFlightInfo({ id }).then((res: any) => {
                if (res.code == 200) {
                    findData()
                    ElMessage({
                        message: '删除成功',
                        type: 'success'
                    })
                }
            })
        })

}


// 添加航班信息弹窗
let dialogHost = ref(false)
let dialogHostTitle = ref('添加航班信息')
const formLabelWidth = '100px'
const addHsotForm = ref<AddFlightInfo>({
    flightNumber: "",
    departureTime: "",
    arrivalTime: "",
    departureCity: "",
    arrivalCity: "",
    airline: "",
    aircraftType: "",
    seatCapacity: undefined,
    ticketNum:  undefined,
    price:  undefined,
    status: undefined,
})

const resetDialogHostFrom = () => {
    addHsotForm.value = {
        flightNumber: "",
        departureTime: "",
        arrivalTime: "",
        departureCity: "",
        arrivalCity: "",
        airline: "",
        aircraftType: "",
        seatCapacity: undefined,
        ticketNum: undefined,
        price: undefined,
        status: undefined,
    }
}

const addHostDialog = () => {
    resetDialogHostFrom()
    dialogHostTitle.value = '添加航班信息'
    dialogHost.value = true
}
const options = ref([
    {
        value: 1, label: '待支付'
    },
    {
        value: 2, label: '取消支付'
    },
    {
        value: 3, label: '支付成功'
    },
])
let paymentStatus = ref('')
let allOrderData = ref<AllOrderInfoRow[]>([])
let dialogHost1 = ref(false)
let flightIdData = ref('')
const findFlightAllOrder = async (flightId: string) => {
    flightIdData.value = flightId
    let params: { paymentStatus?: string | number | undefined, flightId: string, pageNo: number, pageSize: number } = { flightId, pageNo: 1, pageSize: 100 }
    if (paymentStatus) {
        params = { paymentStatus: toValue(paymentStatus), flightId, pageNo: 1, pageSize: 100 }
    }
    await reqFindOrderByFlightId(params).then((res: any) => {
        const { code, data } = res
        if (code === 200) {
            allOrderData.value = data
            dialogHost1.value = true
        } else {
            const message = res.msg || '请求异常'
            ElMessage({
                message: message,
                type: 'warning'
            })
        }
    })
}
let evfaluateArr = ref<EvfaluateRow[]>([])
let dialogHost5 = ref(false)
const findEvaluate = async (flightId: string) => {
    await reqFindEvFaluate({
        flightId,
        pageNo: 1,
        pageSize: 100
    }).then((res: any) => {
        const { code, data, msg } = res

        if (code === 200) {
            evfaluateArr.value = data as EvfaluateRow[]
            dialogHostTitle.value = '该航班全部评价'
            dialogHost5.value = true

        } else if (msg) {
            ElMessage({
                message: msg,
                type: 'warning'
            })
        } else {
            ElMessage({
                message: '请求异常',
                type: 'warning'
            })
        }
    })
}
let orderDetailData = ref<FindMyOrderDetail>()
let dialogHost2 = ref(false)
const findOrderDetail = async (id: string) => {
    await reqFindMyOrderDetail({ id }).then((res: any) => {
        const { data, code, msg } = res
        if (code == 200) {
            orderDetailData.value = data
            dialogHostTitle.value = '查看订单详情'
            dialogHost2.value = true
        } else {
            ElMessage({
                message: msg,
                type: 'error'
            })
        }
    })
}
const changeHandler = () => {
    findFlightAllOrder(flightIdData.value)
}

const addHostSubmit = async () => {
    if (dialogHostTitle.value == '添加航班信息') {
        await reqAddFlightInfo(unref(addHsotForm)).then((res: any) => {
            const { code } = res

            if (code === 200) {
                dialogHost.value = false
                findData()
                ElMessage({
                    message: '添加航班信息成功',
                    type: 'success'
                })

            } else {
                const message = res.msg || '请求异常'
                ElMessage({
                    message: message,
                    type: 'warning'
                })
            }
        })
    } else if (dialogHostTitle.value == '编辑航班信息') {
        await reqModifyFlightInfo({ ...unref(addHsotForm), id: unref(editId) }).then((res: any) => {
            const { code } = res

            if (code === 200) {
                dialogHost.value = false
                findData()
                ElMessage({
                    message: '编辑航班信息',
                    type: 'success'
                })

            } else {
                const message = res.msg || '请求异常'
                ElMessage({
                    message: message,
                    type: 'warning'
                })
            }
        })
    }

}

const isReadonlyHandler = computed(() => {
    return dialogHostTitle.value !== '查看航班信息'
})

</script>

<template>
    <el-card>
        <template #header>
            <div class="card-header">
                <span><strong>航班信息管理</strong></span>
            </div>
        </template>
        <div class="query-input">
            <div><span>航班号: </span>
                <el-input v-model="searchFrom.flightNumber" placeholder="请输入航班号" />
            </div>
            <div><span>出发时间: </span>
                <el-date-picker style="margin-right: 16px;" v-model="searchFrom.departureTime" format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="请选择出发时间" />
            </div>
            <div><span>到达时间: </span>
                <el-date-picker style="margin-right: 16px;" v-model="searchFrom.arrivalTime" format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="请选择到达时间" />
            </div>
            <div><span>出发城市: </span>
                <el-input v-model="searchFrom.departureCity" placeholder="请输入出发城市" />
            </div>
            <div><span>到达城市: </span>
                <el-input v-model="searchFrom.arrivalCity" placeholder="请输入到达城市" />
            </div>
            <div><span>航空公司: </span>
                <el-input v-model="searchFrom.airline" placeholder="请输入航空公司" />
            </div>
            <div><span>飞机型号: </span>
                <el-input v-model="searchFrom.aircraftType" placeholder="请输入飞机型号" />
            </div>
            <el-button type="primary" @click="findData()">
                <el-icon>
                    <Search />
                </el-icon>
                查询
            </el-button>
            <el-button type="danger" @click="reset()">
                <el-icon>
                    <Refresh />
                </el-icon>
                重置
            </el-button>
        </div>

    </el-card>

    <el-card>
        <div>
            <el-button key="'添加航班信息'" @click="addHostDialog()" :icon="CirclePlus" type="primary" text bg
                class="addUser">添加航班信息</el-button>
        </div>
        <el-table :data="tableData" stripe style="width: 100%">
            <el-table-column prop="airline" label="航空公司" />
            <el-table-column prop="aircraftType" label="飞机型号" width="150" />
            <el-table-column prop="flightNumber" label="航班号" />
            <el-table-column prop="departureTime" label="出发时间" width="180" />
            <el-table-column prop="arrivalTime" label="到达时间" width="180" />
            <el-table-column prop="departureCity" label="出发城市" />
            <el-table-column prop="arrivalCity" label="到达城市" />
            <el-table-column fixed="right" label="操作" width="280">
                <template #default="scope">
                    <el-space wrap>
                        <el-button type="primary" size="small" plain @click="findRoleInfo(scope.row.id)">查看航班信息</el-button>
                        <el-button type="primary" size="small" plain @click="editRoleInfo(scope.row.id)">编辑</el-button>
                        <el-button type="danger" size="small" color="red" plain
                            @click="deleteRoleInfo(scope.row.id)">删除</el-button>
                        <el-button type="danger" size="small" color="red" plain
                            @click="findFlightAllOrder(scope.row.id)">查看订单信息</el-button>
                        <el-button type="danger" size="small" color="red" plain
                            @click="findEvaluate(scope.row.id)">查看全部评价</el-button>
                    </el-space>
                </template>
            </el-table-column>

        </el-table>

        <div class="demo-pagination-block">
            <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
                :background="false" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </el-card>
    <!-- 添加航班信息弹框 -->
    <el-dialog v-model="dialogHost" :title="dialogHostTitle">
        <el-form :model="addHsotForm">
            <el-form-item label="航班号:" :label-width="formLabelWidth" clearable required>
                <el-input v-model="addHsotForm.flightNumber" autocomplete="off" placeholder="请输入航班号"
                    :disabled="!isReadonlyHandler" />
            </el-form-item>
            <el-form-item label="出发时间:" :label-width="formLabelWidth" clearable required>
                <el-date-picker :disabled="!isReadonlyHandler" v-model="addHsotForm.departureTime"
                    format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="请选择出发时间" />
            </el-form-item>
            <el-form-item label="到达时间:" :label-width="formLabelWidth" clearable required>
                <el-date-picker :disabled="!isReadonlyHandler" v-model="addHsotForm.arrivalTime"
                    format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="请选择到达时间" />
            </el-form-item>
            <el-form-item label="出发城市:" :label-width="formLabelWidth" clearable required>
                <el-input v-model="addHsotForm.departureCity" placeholder="请输入出发城市" :disabled="!isReadonlyHandler" />
            </el-form-item>
            <el-form-item label="到达城市:" :label-width="formLabelWidth" clearable required>
                <el-input v-model="addHsotForm.arrivalCity" placeholder="请输入到达城市" :disabled="!isReadonlyHandler" />
            </el-form-item>
            <el-form-item label="航空公司:" :label-width="formLabelWidth" clearable required>
                <el-input v-model="addHsotForm.airline" placeholder="请输入航空公司" :disabled="!isReadonlyHandler" />
            </el-form-item>
            <el-form-item label="飞机型号:" :label-width="formLabelWidth" clearable required>
                <el-input v-model="addHsotForm.aircraftType" placeholder="请输入飞机型号" :disabled="!isReadonlyHandler" />
            </el-form-item>
            <el-form-item label="座位容量:" :label-width="formLabelWidth" clearable required>
                <el-input-number v-model="addHsotForm.seatCapacity" placeholder="请输入座位容量" :disabled="!isReadonlyHandler" />
            </el-form-item>
            <el-form-item label="剩余票数:" :label-width="formLabelWidth" clearable required>
                <el-input-number v-model="addHsotForm.ticketNum" placeholder="请输入剩余票数" :disabled="!isReadonlyHandler" />
            </el-form-item>
            <el-form-item label="价格:" :label-width="formLabelWidth" clearable required>
                <el-input-number v-model="addHsotForm.price" placeholder="请输入价格" :disabled="!isReadonlyHandler" />
            </el-form-item>

        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogHost = false">取消</el-button>
                <el-button v-if="isReadonlyHandler" type="primary" @click="addHostSubmit()">
                    确认
                </el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 订单全部详情弹窗 -->
    <el-dialog v-model="dialogHost1" title="订单详情" width="950px">
        <div><span>支付状态: </span>
            <el-select v-model="paymentStatus" @change="changeHandler()" clearable class="m-2" placeholder="请选择支付状态"
                style="width: 240px">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
        </div>
        <el-table :data="allOrderData" stripe style="width: 100%;margin-top:18px">
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="phone" label="电话号码" width="100" />
            <el-table-column prop="email" label="电子邮件" width="140" />
            <el-table-column prop="ordersTime" label="下单时间" width="180" />
            <el-table-column prop="paymentTime" label="付款时间" width="180" />
            <el-table-column prop="cancelTime" label="取消时间" />
            <el-table-column label="支付状态">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <el-tag v-if="scope.row.paymentStatus == 1" type="warning">待支付</el-tag>
                            <el-tag v-if="scope.row.paymentStatus == 3" type="success">支付成功</el-tag>
                            <el-tag v-if="scope.row.paymentStatus == 2" type="info">取消支付</el-tag>
                        </div>
                    </template>
                </el-table-column>
            <el-table-column fixed="right" label="操作" width="120">
                <template #default="scope">
                    <el-space wrap>
                        <el-button type="primary" size="small" plain
                            @click="findOrderDetail(scope.row.orderId)">查看订单详情</el-button>
                    </el-space>
                </template>
            </el-table-column>

        </el-table>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogHost1 = false">取消</el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 查看订单弹框 -->
    <el-dialog v-model="dialogHost2" title="订单详情">
        <el-descriptions class="margin-top"
            :title="orderDetailData?.paymentStatus == 1 ? '待支付' : orderDetailData?.paymentStatus == 2 ? '取消支付' : '支付成功'"
            :column="3" border>
            <el-descriptions-item>
                <template #label>
                    <div class="cell-item">
                        航班号
                    </div>
                </template>
                {{ orderDetailData?.flightNumber }}
            </el-descriptions-item>
            <el-descriptions-item>
                <template #label>
                    <div class="cell-item">
                        出发时间
                    </div>
                </template>
                {{ orderDetailData?.departureTime }}
            </el-descriptions-item>
            <el-descriptions-item>
                <template #label>
                    <div class="cell-item">
                        到达时间
                    </div>
                </template>
                {{ orderDetailData?.arrivalTime }}
            </el-descriptions-item>
            <el-descriptions-item>
                <template #label>
                    <div class="cell-item">
                        出发城市
                    </div>
                </template>
                {{ orderDetailData?.departureCity }}
            </el-descriptions-item>
            <el-descriptions-item>
                <template #label>
                    <div class="cell-item">
                        到达城市
                    </div>
                </template>
                {{ orderDetailData?.arrivalCity }}
            </el-descriptions-item>
            <el-descriptions-item>
                <template #label>
                    <div class="cell-item">
                        航空公司
                    </div>
                </template>
                {{ orderDetailData?.airline }}
            </el-descriptions-item>
            <el-descriptions-item>
                <template #label>
                    <div class="cell-item">
                        飞机型号
                    </div>
                </template>
                {{ orderDetailData?.aircraftType }}
            </el-descriptions-item>
            <el-descriptions-item>
                <template #label>
                    <div class="cell-item">
                        座位容量
                    </div>
                </template>
                {{ orderDetailData?.seatCapacity }}
            </el-descriptions-item>
            <el-descriptions-item>
                <template #label>
                    <div class="cell-item">
                        价格
                    </div>
                </template>
                {{ orderDetailData?.price }}
            </el-descriptions-item>
            <el-descriptions-item>
                <template #label>
                    <div class="cell-item">
                        支付状态
                    </div>
                </template>
                {{ orderDetailData?.paymentStatus == 1 ? '待支付' : orderDetailData?.paymentStatus == 2 ? '取消支付' : '支付成功' }}
            </el-descriptions-item>
            <el-descriptions-item>
                <template #label>
                    <div class="cell-item">
                        下单时间
                    </div>
                </template>
                {{ orderDetailData?.ordersTime }}
            </el-descriptions-item>
            <el-descriptions-item>
                <template #label>
                    <div class="cell-item">
                        支付时间
                    </div>
                </template>
                {{ orderDetailData?.paymentTime }}
            </el-descriptions-item>
            <el-descriptions-item>
                <template #label>
                    <div class="cell-item">
                        取消时间
                    </div>
                </template>
                {{ orderDetailData?.cancelTime }}
            </el-descriptions-item>

        </el-descriptions>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogHost2 = false">取消</el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 查看评价弹框 -->
    <el-dialog v-model="dialogHost5" title="当前订单全部评价">
        <el-table :data="evfaluateArr" stripe style="width: 100%">
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="score" label="分数">
                <template #default="scope">
                    <el-rate v-model="scope.row.score" allow-half :disabled="true" />
                </template>
            </el-table-column>
            <el-table-column prop="comment" label="内容" />
        </el-table>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogHost5 = false">取消</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style scoped>
.el-input {
    margin-right: 5px;
    width: 400px;
    margin-right: 16px;
}

.query-input {
    font-size: 14px;
    font-family: 'Courier New', Courier, monospace;
    font-weight: 700;
    display: flex;
    gap: 10;
    align-items: center;
    justify-content: start;
    flex-wrap: wrap;
    height: 200px;
}

.el-card {
    margin-bottom: 10px;
}

.demo-pagination-block {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

.addUser {
    float: right;
    margin-right: 10px;
}

.el-button--text {
    margin-right: 15px;
}

.el-select {
    width: 300px;
}

/* 
.el-input & .el-textarea  {
  width: 300px;
} */
.el-textarea {
    width: 400px;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}
</style>